<template>
  <el-dialog title="添加分类" :visible.sync="dialogVisible" width="46%" @close='clear'>
    <!-- 主体表单区域 -->
    <el-form ref="formRef" :model="addForm" label-width="80px" :rules="formRules">
      <el-form-item label="分类名称" prop="cat_name">
        <el-input v-model="addForm.cat_name" clearable></el-input>
      </el-form-item>
      <el-form-item label="活动名称">
        <el-cascader v-model="selectedKeys" :options="parentCateList" :props="cascaderProps" @change="handleChange" clearable>
        </el-cascader>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data: function () {
    return {
      // 设置对话框显隐
      dialogVisible: false,
      addForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 父级分类的列表
      parentCateList: [],
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 指定级联选择器配置问题
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 添加分类表单的校验规则
      formRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取父级分类的数据列表
    getParentCateList: async function () {
      const res = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.warning('获取父级数据失败')
      }
      this.parentCateList = res.data
    },
    handleChange: function () {
      // 如果selectedKeys数组中的长度大于0，证明选中了父级分类
      // 反之，没有选择任何父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的id值
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        // 为当前分类的等级赋值
        this.addForm.cat_level = this.selectedKeys.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // 点击确认，添加分类
    confirm: function () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.post('categories', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.warning('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.dialogVisible = false
        this.$parent.getCateList()
      })
    },
    // 清空历史痕迹
    clear: function () {
      this.$refs.formRef.resetFields()
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_name = ''
      this.addForm.cat_level = 0
    }
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
</style>
